import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:xbaistack/router.dart';

class GalleryViewPageArguments {
  final List<String> images;
  final int initialIndex;
  const GalleryViewPageArguments(this.images, {this.initialIndex = 0});
}

class GalleryViewPage extends StatefulWidget
    with RouterBridge<GalleryViewPageArguments> {
  const GalleryViewPage({super.key});

  @override
  State<StatefulWidget> createState() => _GalleryViewPageState();
}

class _GalleryViewPageState extends State<GalleryViewPage> {
  int pageIndex = 0;
  // PageController? pageController;

  @override
  void initState() {
    super.initState();
   
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        // 获取路由参数，设置初始图片索引
        final args = widget.argumentOf(context);
        pageIndex = args?.initialIndex ?? 0;
        // pageController = PageController(initialPage: pageIndex);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // 图片列表（路由参数，同上）
    final images = widget.argumentOf(context);
    // if (pageController == null) {
    //   return const Center(child: CircularProgressIndicator());
    // }
    return Scaffold(
      appBar: AppBar(
        shape: const Border(),
        leading: const CloseButton(),
        foregroundColor: Colors.white,
        backgroundColor: Colors.transparent,
        title: Text("${pageIndex + 1}/${images?.images.length}"), // 显示图片序号
      ),
      backgroundColor: Colors.black,
      extendBodyBehindAppBar: true,
      body: PhotoViewGallery.builder(
        itemCount: images?.images.length,
        // 启用图片旋转功能
        enableRotation: true,

        // 监听图片切换，用于配合导航栏更新图片序号
        onPageChanged: changeIndex,
        // 滚动效果配置
        scrollPhysics: const AlwaysScrollableScrollPhysics(
          parent: BouncingScrollPhysics(),
        ),
        pageController: PageController(
          initialPage: images?.initialIndex ?? 0,
        ),
        // 构造图片
        builder: (context, index) {
          return PhotoViewGalleryPageOptions(
            imageProvider: CachedNetworkImageProvider(
              images?.images[index] ?? '',
            ),
            // imageProvider: NetworkImage(images![index]),
            // 初始化缩放倍率
            initialScale: PhotoViewComputedScale.contained * 0.8,
            // Hero 配置
            heroAttributes: PhotoViewHeroAttributes(
              tag: images?.images[index] ?? '',
            ),
          );
        },
      ),
    );
  }

  void changeIndex(int page) {
    setState(() => pageIndex = page);
  }
}
